<template>
    <div class="user-header">
        <el-button type="primary" @click="addHandle">+新增</el-button>
        <el-form :inline="true" :model="seaechForm">
            <el-form-item label="请输入">
                <el-input v-model="seaechForm.keyword" placeholder="请输入用户名" />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="handleSearch">搜索</el-button>
            </el-form-item>
        </el-form>
    </div>
    <div class="table">
        <el-table :data="userList" style="width: 100%;">
            <el-table-column v-for="item in tableList" :width="item.width ? item.width : 180" :key="item.props"
                :prop="item.props" :label="item.label" />
            <el-table-column fixed="right" label="操作" min-width="180">
                <template #default="scope">
                    <el-button size="small" @click="handleEdit(scope.row)">
                        编辑
                    </el-button>
                    <el-button link type="danger" size="small" @click="delHandle(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination size="small" class="mt-4 pager" @current-change="changePage" background layout="prev, pager, next"
            :total="config.total" v-model:current-page="config.page" />
    </div>
    <el-dialog v-model="dialogVisible" :title="formTitle == 'add' ? '新增用户' : '编辑用户'" width="600"
        :before-close="handleClose">
        <el-form :inline="true" :model="formData" ref="userFormRef" :rules="rules">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="formData.name" placeholder="请输入姓名" clearable />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="年龄" prop="age">
                        <el-input v-model.number="formData.age" placeholder="请输入年龄" clearable />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="性别" prop="sex">
                        <el-select style="width: 180px;" v-model="formData.sex" placeholder="请选择">
                            <el-option label="男" value="0" />
                            <el-option label="女" value="1" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="出生日期" prop="birth">
                        <el-date-picker value-format="YYYY-MM-DD" v-model="formData.birth" type="date" placeholder="请输入"
                            style="width: 100%" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-form-item label="地址" prop="address">
                    <el-input v-model="formData.address" placeholder="请输入地址" clearable />
                </el-form-item>
            </el-row>
            <el-row style="justify-content: flex-end;">
                <el-form-item>
                    <el-button type="primary" @click="onSubmit()">确定</el-button>
                    <el-button type="primary" @click="resetForm(userFormRef)">重置</el-button>
                </el-form-item>
            </el-row>
        </el-form>
    </el-dialog>
</template>

<script setup>
import { tabelListApi, userListApi, addUserApi, editUserApi, delUserApi } from '@/service/userListApi.js';
import { nextTick, onMounted, reactive, ref } from 'vue';
const config = reactive({
    page: 1,
    total: 0,
    name: ''
})
const userFormRef = ref();
const formTitle = ref('add')
const tableList = ref([])
const userList = ref([])
const dialogVisible = ref(false)
const formData = reactive({
    name: '',
    age: '',
    sex: "",
    birth: '',
    address: ''
})
const rules = reactive({
    name: [{ required: true, whitespace: true, message: '姓名不能为空', trigger: 'blur' }],
    age: [
        { required: true, message: '年龄不能为空' },
        { type: 'number', message: '年龄必须为数字' },
    ],
    sex: [
        { required: true, whitespace: true, message: '性别不能为空', trigger: 'blur' }
    ],
    birth: [{ required: true, whitespace: true, message: '出生日期不能为空', trigger: 'blur' },
    ],
    address: [{ required: true, message: '地址不能为空' },
    ]

})
const seaechForm = reactive({
    keyword: ''
})
onMounted(() => {
    getTabelList(), getUserList(config)
})
const handleSearch = () => {
    config.name = seaechForm.keyword
    config.page = 1;
    getUserList(config)

}
const addHandle = () => {
    formTitle.value = 'add',
        Object.assign(formData, {
            name: '',
            age: '',
            sex: '',
            birth: '',
            address: ''
        })
    dialogVisible.value = true
}

const getTabelList = async () => {
    let res = await tabelListApi();
    tableList.value = res.data
}
const getUserList = async (config) => {
    let res = await userListApi(config);
    config.total = res.data.total
    userList.value = res.data.list.map((item) => {
        item.sex = Number(item.sex) === 1 ? '女' : '男';
        return item
    })
}

const handleEdit = (row) => {
    formTitle.value = 'edit'
    dialogVisible.value = true;
    // row.sex === 1 ? (row.sex = '女') : (row.sex = '男');
    nextTick(() => {
        Object.assign(formData, row)
    })
}
const delHandle = (row) => {
    ElMessageBox.confirm('确定删除吗？')
        .then(async () => {
            let res = await delUserApi(row.id)
            console.log('200');
            if (res.code === 200) {
                ElMessage({
                    showClose: true,
                    message: '删除成功',
                    type: 'success'
                })
                getUserList(config)
            }
        })
        .catch(() => {
        })
}
const changePage = (page) => {
    config.page = page
    getUserList(config)
}
const onSubmit = () => {
    if (!userFormRef.value) return;
    userFormRef.value.validate(async valid => {
        if (valid) {
            if (formTitle.value === 'add') {
                console.log('111');
                let res = await addUserApi(formData)
                if (res.code === 200) {
                    dialogVisible.value = false;
                    resetForm(userFormRef.value)
                    await getUserList(config)
                }
            } else {
                // formData.sex == '男' ? (formData.sex = 0) : (formData.sex = 1);
                let res = await editUserApi(formData)
                if (res.code === 200) {
                    dialogVisible.value = false;
                    resetForm(userFormRef.value)
                    getUserList(config)
                }
            }
        } else {
            ElMessage({
                showClose: true,
                message: '请输入正确信息',
                type: 'error'
            })
        }
    })
}
const handleClose = (done) => {
    ElMessageBox.confirm('确定要关闭吗？')

        .then(() => {
            resetForm(userFormRef.value)
            dialogVisible.value=false
            done()
        })
        .catch(() => {
        })
}
const resetForm = (form) => {
    form.resetFields()
}
</script>
<style lang='scss' scoped>
.user-header {
    display: flex;
    justify-content: space-between;
}
</style>